package com.ruowei.modules.sys.service;

import com.querydsl.jpa.impl.JPAQueryFactory;
import com.ruowei.modules.foodOrder.domain.*;
import com.ruowei.modules.foodOrder.repository.CourierOnlineLogRepository;
import com.ruowei.modules.foodOrder.repository.CouriersRepository;
import com.ruowei.modules.foodOrder.repository.MerchantRepository;
import com.ruowei.modules.sys.domain.LoginRelatedLog;
import com.ruowei.modules.sys.domain.enumeration.UserType;
import com.ruowei.modules.sys.domain.table.SysUserTable;
import com.ruowei.modules.sys.repository.LoginRelatedLogRepository;
import com.ruowei.modules.sys.repository.SysRoleRepository;
import com.ruowei.modules.sys.repository.SysUserRoleRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Optional;

@Service
@Transactional
public class UserJWTService {
    private final QCouriers qCouriers = QCouriers.couriers;
    private final QMerchant qMerchant = QMerchant.merchant;

    private final SysUserRoleRepository sysUserRoleRepository;
    private final SysRoleRepository sysRoleRepository;
    private final LoginRelatedLogRepository loginRelatedLogRepository;
    private final JPAQueryFactory queryFactory;
    private final CourierOnlineLogRepository courierOnlineLogRepository;
    private final MerchantRepository merchantRepository;
    private final CouriersRepository couriersRepository;

    public UserJWTService(SysUserRoleRepository sysUserRoleRepository, SysRoleRepository sysRoleRepository, LoginRelatedLogRepository loginRelatedLogRepository, JPAQueryFactory queryFactory, CourierOnlineLogRepository courierOnlineLogRepository, MerchantRepository merchantRepository, CouriersRepository couriersRepository) {
        this.sysUserRoleRepository = sysUserRoleRepository;
        this.sysRoleRepository = sysRoleRepository;
        this.loginRelatedLogRepository = loginRelatedLogRepository;
        this.queryFactory = queryFactory;
        this.courierOnlineLogRepository = courierOnlineLogRepository;
        this.merchantRepository = merchantRepository;
        this.couriersRepository = couriersRepository;
    }

    public void logout(SysUserTable sysUser) {
        // 新建登出日志
        LoginRelatedLog loginRelatedLog = new LoginRelatedLog();
        ZonedDateTime nowTime = ZonedDateTime.now(ZoneId.systemDefault());
        loginRelatedLog.setLoginCode(sysUser.getLoginCode());
        loginRelatedLog.setOperateTime(nowTime);
        loginRelatedLog.setOperateType("登出");
        loginRelatedLog.setUserName(sysUser.getUserName());
        // 获取userRole
        Long userId = sysUser.getId();
        Long roleId = sysUserRoleRepository.findAllBySysUserId(userId).get(0).getSysRoleId();
        String roleName = null;
        if (sysRoleRepository.findById(roleId).isPresent()) {
            roleName = sysRoleRepository.findById(roleId).get().getRoleName();
        }
        loginRelatedLog.setUserRole(roleName);
        // 保存登出日志
        loginRelatedLogRepository.save(loginRelatedLog);
    }

    public void online(SysUserTable sysUser) {
        if (sysUser.getUserType().equals(UserType.COURIER)) {
            //配送员状态变为上线，保存日志
            Optional<Couriers> optionalCouriers = couriersRepository.findFirstByCourierCode(sysUser.getUserCode());
            if (optionalCouriers.isPresent() && optionalCouriers.get().isAvailableStatus()) {
                Couriers couriers = optionalCouriers.get();
                couriers.setOnLineStatus(true);
                couriersRepository.saveAndFlush(couriers);
            }
            CourierOnlineLog courierOnlineLog = new CourierOnlineLog();
            courierOnlineLog.setCourierCode(sysUser.getUserCode());
            courierOnlineLog.setTime(Instant.now());
            courierOnlineLog.setType("上线");
            courierOnlineLogRepository.save(courierOnlineLog);
        }
//        if (sysUser.getUserType().equals(UserType.BUSINESS)) {
//            //商家状态 改为营业
//            Optional<Merchant> optionalMerchant = merchantRepository.findByMerchantCode(sysUser.getUserCode());
//            if (optionalMerchant.isPresent() && !optionalMerchant.get().getStatus().equals("删除")){
//                Merchant merchant = optionalMerchant.get();
//                merchant.setStatus("营业");
//                merchantRepository.saveAndFlush(merchant);
//            }
//        }
    }

    public void offline(SysUserTable sysUser) {
        if (sysUser.getUserType().equals(UserType.COURIER)) {
            //配送员状态变为下线，保存日志
            Optional<Couriers> optionalCouriers = couriersRepository.findFirstByCourierCode(sysUser.getUserCode());
            if (optionalCouriers.isPresent() && optionalCouriers.get().isAvailableStatus()) {
                Couriers couriers = optionalCouriers.get();
                couriers.setOnLineStatus(false);
                couriersRepository.saveAndFlush(couriers);
            }
            CourierOnlineLog courierOnlineLog = new CourierOnlineLog();
            courierOnlineLog.setCourierCode(sysUser.getUserCode());
            courierOnlineLog.setTime(Instant.now());
            courierOnlineLog.setType("下线");
            courierOnlineLogRepository.save(courierOnlineLog);
        }
//        if (logout && sysUser.getUserType().equals(UserType.BUSINESS)) {
//            //商家状态如果是营业 改为歇业
//            Optional<Merchant> optionalMerchant = merchantRepository.findByMerchantCode(sysUser.getUserCode());
//            if (optionalMerchant.isPresent() && optionalMerchant.get().getStatus().equals("营业")){
//                Merchant merchant = optionalMerchant.get();
//                merchant.setStatus("歇业");
//                merchantRepository.saveAndFlush(merchant);
//            }
//        }
    }
}
